<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + ''"
    width="800px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import { listMenu } from "@/api/system/menu";
import { getItemDetail, addItem, editItem } from "@/api/navset/index.js";

import FormButton from "@/components/FormButton";
export default {
  dicts: ["nav_special", "nav_type"],
  components: {
    FormButton,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    configId: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    disabledFalge: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      menuList: [],
      parentId: null, //  父节点ID
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              name: [
                {
                  required: true,
                  message: "请输入菜单模块名称",
                  trigger: "blur",
                },
                {
                  validator: function (rule, value, callback) {
                    let reg = new RegExp(
                      "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                    );
                    if (!reg.test(value)) {
                      callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur",
                },
              ],
              subheading: [
                {
                  required: true,
                  message: "请输入副标题名称",
                  trigger: "blur",
                },
                // {
                //   validator: function (rule, value, callback) {
                //     let reg = new RegExp(
                //       "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                //     );
                //     if (!reg.test(value)) {
                //       callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                //     } else {
                //       callback();
                //     }
                //   },
                //   trigger: "blur",
                // },
              ],
              sysMenuId: [
                {
                  required: false,
                  message: "请选择系统菜单",
                  trigger: "change",
                },
              ],
              disable: [
                {
                  required: true,
                  message: "请选择是否禁用",
                  trigger: "change",
                },
              ],
              logImg1: [
                {
                  required: false,
                  message: "请选择模块Logo",
                  trigger: "change",
                },
              ],
              logImg2: [
                {
                  required: false,
                  message: "请选择模块底图",
                  trigger: "change",
                },
              ],
              special: [
                {
                  required: false,
                  message: "请选择特殊动作",
                  trigger: "change",
                },
              ],
              type: [
                {
                  required: true,
                  message: "请选择路由级别",
                  trigger: "change",
                },
              ],
              // parameters: [
              //   {
              //     required: false,
              //     message: "请输入特殊参数",
              //     trigger: "blur",
              //   },
              //   {
              //     validator: function (rule, value, callback) {
              //       let reg = new RegExp(
              //         "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
              //       );
              //       if (!reg.test(value)) {
              //         callback("请勿输入特殊字符，且不能以下划线开头和结尾");
              //       } else {
              //         callback();
              //       }
              //     },
              //     trigger: "blur",
              //   },
              // ],
            },
          },
          properties: {
            name: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "菜单模块名称",
              typeName: "el-input",
              disabled: false,
            },
            subheading: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "副标题名称",
              typeName: "el-input",
              disabled: false,
            },
            sysMenuId: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "系统菜单",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [...that.menuList];
                let valNum = that.$refs?.form?.getFieldsValue().sysMenuId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择系统菜单",
                        value: valNum,
                        clearable: true,
                        disabled: that.disabledFalge,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("sysMenuId", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            disable: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "是否禁用",
              typeName: "el-select",
              disabled: false,
              options: [
                {
                  label: "否",
                  value: 0,
                },
                {
                  label: "是",
                  value: 1,
                },
              ],
            },
            logImg1: {
              label: "模块Logo",
              typeName: "ImageUpload",
              limit: 1,
              fileSize: 5,
              accept: "image/*",
              fileBigness: "85*85px",
              disabled: false,
            },
            logImg2: {
              label: "模块底图",
              typeName: "ImageUpload",
              limit: 1,
              fileSize: 5,
              accept: "image/*",
              fileBigness: "454*614px",
              disabled: false,
            },
            special: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "特殊动作",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.nav_special.some((item) => {
                  arr.push(item);
                });
                let valNum = that.$refs?.form?.getFieldsValue().special;
                if (valNum != null && valNum != undefined) {
                  valNum = valNum + "";
                }
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择特殊动作",
                        value: valNum,
                        clearable: true,
                        disabled: that.disabledFalge,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("special", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            type: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "路由级别",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.nav_type.some((item) => {
                  arr.push(item);
                });
                let valNum = that.$refs?.form?.getFieldsValue().type;
                if (valNum != null && valNum != undefined) {
                  valNum = valNum + "";
                }
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择路由级别",
                        value: valNum,
                        clearable: true,
                        disabled: that.disabledFalge,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("type", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            orderNum: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "显示排序",
              typeName: "el-input-number",
              disabled: false,
            },
            parameters: {
              bsColumn: {
                col: 2,
                middle: true,
              },
              label: "特殊参数",
              typeName: "el-input",
              disabled: false,
            },
          },
        },
      },
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.getMenulist();
          this.disableDeal();
          if (this.operateType == "detail" || this.operateType == "edit") {
            if (String(this.id).length > 0) {
              this.getInfo();
            }
          } else if (this.operateType == "addchildren") {
            this.parentId = this.id;
            console.log(this.parentId, "parentId");
          }
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    getMenulist() {
      this.menuList = [];
      listMenu({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              if (item.menuType == "C") {
                let obj = {
                  label: item?.menuName,
                  value: item?.menuId,
                };
                this.menuList.push(obj);
              }
            });
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 请求详情
    getInfo() {
      getItemDetail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data ?? {};
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    disableDeal() {
      this.apsForm.formConfig.properties.name.disabled = this.disabledFalge;
      this.apsForm.formConfig.properties.subheading.disabled =
        this.disabledFalge;
      this.apsForm.formConfig.properties.disable.disabled = this.disabledFalge;
      this.apsForm.formConfig.properties.logImg1.disabled = this.disabledFalge;
      this.apsForm.formConfig.properties.logImg2.disabled = this.disabledFalge;
      this.apsForm.formConfig.properties.orderNum.disabled = this.disabledFalge;
      this.apsForm.formConfig.properties.parameters.disable =
        this.disabledFalge;
    },
    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      data.configId = this.configId; // 赋予配置对象的id
      if (this.disabledFalge) {
        this.handleClose(false);
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true;
            if (this.operateType == "edit") {
              this.editRequest(data);
            } else if (
              this.operateType == "addfather" ||
              this.operateType == "addchildren"
            ) {
              this.addRequest(data);
            }
          } else {
            return false;
          }
        });
      }
    },
    addRequest(data) {
      if (this.operateType == "addfather") {
        data.parentId = null;
      } else {
        data.parentId = this.parentId;
      }
      addItem(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    editRequest(data) {
      data.id = this.id;
      editItem(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
